<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<script name="router.js">
			function Router() {

				this.routes = []

				/* 添加路由 */
				this.add = function(re, handler) {
					this.routes.push({
						re,
						handler
					})
				}

				/* 监听 url 变化  */
				this.listen = function() {
					//路由切换
					window.addEventListener('hashchange', function(event) {
						var hash = window.location.hash
						for (var i = 0; i++; i < this.routes.length) {
							if (hash === this.routes[i].re) {
								this.routes[i].handler.apply({})
							}
						}
					}, false)
				}

				/* 前进到一个新的url  */
				this.push = function(path) {
					window.location.hash = path || ''
				}

				/* 替换成一个新的url  */
				this.replace = function(path) {
					path = path || ''
					var i = window.location.href.indexOf('#')
					window.location.replace(window.location.href.slice(0, i >= 0 ? i : 0) + "#" + path)
				}

				/* 返回到上一个url  */
				this.back = function() {
					window.history.back()
				}
			}
		</script>

	</head>
	<body>
		<div>
			<button id="btn">点击跳转到 list</button>
			<button id="btn2">点击跳转到 detail</button>
		</div>
		<script>
			var router = new Router();

			router.add('/list', function() {

			})
			router.add('/detail', function() {

			})

			router.listen();


			var btn = document.getElementById('btn');
			btn.addEventListener('click', function(e) {
				router.push('/list')
			});
			btn2.addEventListener('click', function(e) {
				router.push('/detail')
			});
		</script>
	</body>
</html>